	
window.onload=function(){
	var curr = 0;
	var prev = curr;
	var reel = document.getElementById("reel");
	var maxCard = reel.getElementsByClassName("card").length-1;
	var elem;
	var navs = document.getElementsByClassName("navthumb");
	var cards = document.getElementsByClassName("card-container");
	var buttons = document.getElementsByClassName("button");
	initListeners();
	initFocus();
	
	function nextCard(){
		prev=curr;
		if(curr>=maxCard) curr=-1;
		changeCard(++curr);
	}
	function lastCard(){
		prev=curr;
		if(curr<=0) curr=maxCard+1;
		changeCard(--curr);
	}
	function changeCard(card){
		if (card==prev) return;
		reel.style.left=-850*(card) + "px";
		navs[card].classList.add("focus");
		navs[prev].classList.remove("focus");
	}
	function flip(e){
		if(e.target.tagName.toLowerCase()=="input") return;
		if(cards[curr].classList.contains("flip")) return;
		cards[curr].classList.toggle("flip");
	}
	function flipback(){
		if(cards[curr].classList.contains("flip")) cards[curr].classList.toggle("flip");
	}
	function initArrowListeners(){
		document.onkeydown = function(e) {
			e = e || window.event;
			if (document.activeElement.tagName.toLowerCase()=="input") return;
			switch(e.which || e.keyCode) {
				case 37: // left
				lastCard(); break;
				case 39: // right
				nextCard(); break;
				default: return; // exit this handler for other keys
			}
			e.preventDefault(); // prevent the default action (scroll / move caret)
		};
	}
	function initCardListeners(){
		var index;
		for (index=0; index<cards.length; index++){
			cards[index].addEventListener("click", function(e){flip(e)}, false);
		}
	}
	function initButtonListeners(){
		var index;
		for (index=0; index<buttons.length; index++){
			buttons[index].addEventListener("click", function(e){ flipback()}, false);
		}
	}
	function initNavListeners(){
		var index;
		for (index=0; index<navs.length; index++){
			navs[index].addEventListener("click", function(e){ prev=curr; curr=e.target.id-1; changeCard(curr); }, false);
		}
	}
	function initFocus(){
		navs[prev].classList.add("focus");
	}
	function initListeners(){
		initArrowListeners();
		initCardListeners();
		initNavListeners();
		initButtonListeners();
	}
}

